<%@page import="org.dbstar.scheduler.beans.CmdJobConf"%>
<%@page import="org.dbstar.scheduler.beans.CompoundJobConf"%>
<%@page import="org.dbstar.scheduler.beans.LoopJobConf"%>
<%@page import="org.dbstar.scheduler.control.JobConfController"%>
<%@page import="org.dbstar.scheduler.beans.JobConf"%>
<%@page import="org.dbstar.scheduler.beans.JobDefine"%>
<%@page import="org.dbstar.scheduler.beans.CompoundJob"%>
<%@page import="java.io.IOException"%>
<%@page import="org.dbstar.scheduler.control.JobController"%>
<%@page import="org.dbstar.scheduler.beans.Job"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="common/taglibs.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%!
int addTask(CompoundJob job, JobConf conf, JobController jobController, JobConfController jobConfController, JspWriter out, String parentTask, int dep) throws Exception {
	int index = 0;
	int count = 0;
	for (JobDefine jd: job.getSubJobs()) {
		Job subJob;
		JobConf subConf;
		long launchTime;
		float duration;
		if (!jd.isSkip()) {
			subJob = jobController.getJob(jd.getIdentifier());
			subConf = jobConfController.getJobConf(subJob.getJobConfIdentifier());
			launchTime = subJob.getLaunchTime();
			duration = (subJob.getFinishTime()-subJob.getLaunchTime())/3600000f;
		} else {
			subJob = null;
			if (LoopJobConf.JOB_TYPE.equals(conf.getType())) {
				subConf = jobConfController.getJobConf(((LoopJobConf)conf).getSubJob().getIdentifier());
			} else {
				subConf = jobConfController.getJobConf(((CompoundJobConf)conf).getJob(index).getIdentifier());
			}
			launchTime = job.getLaunchTime();
			if (jd.getDependencies()!=null) {
				for (int i: jd.getDependencies()) {
					JobDefine sjd = job.getSubJobs().get(i-1);
					if (!sjd.isSkip()) {
						Job depJob = jobController.getJob(sjd.getIdentifier());
						launchTime = Math.max(launchTime, depJob.getFinishTime());
					}
				}
			}
			duration = 0f;
		}
		String id = jd.getIdentifier().getStringIdentifier();
		String name = subConf.getName();
		int percentCompleted = 100;
		String predecessorTaskId = "";
		if (jd.getDependencies()!=null) {
			for (int i: jd.getDependencies()) {
				predecessorTaskId = job.getSubJobs().get(i-1).getIdentifier().getStringIdentifier();
			}
		}
		
		if (subJob!=null && CompoundJobConf.JOB_TYPE.equals(subJob.getType())) {
			String varTsk = "tsk_" + jd.getIdentifier().getStringIdentifier();
			out.println("var " + varTsk + " = new GanttTaskInfo('" + id + "', '" + name + "', new Date(" + launchTime + "), " + duration + ", " + percentCompleted + ", '" + predecessorTaskId + "');");
			if (job.getSubJobs().size()<=30 && count < 100 && dep <3) {
				count+=addTask((CompoundJob)subJob, subConf, jobController, jobConfController, out, varTsk, dep+1);
			}
			if (parentTask!=null) {
				out.println(parentTask + ".addChildTask(" + varTsk + ");");
			} else {
				out.println("project1.addTask(" + varTsk + ");");
			}
			count++;
		} else {
			if (parentTask!=null) {
				out.println(parentTask + ".addChildTask(new GanttTaskInfo('" + id + "', '" + name + "', new Date(" + launchTime + "), " + duration + ", " + percentCompleted + ", '" + predecessorTaskId + "'));");
			} else {
				out.println("project1.addTask(new GanttTaskInfo('" + id + "', '" + name + "', new Date(" + launchTime + "), " + duration + ", " + percentCompleted + ", '" + predecessorTaskId + "'));");
			}
			count++;
		}
		
		index++;
	}
	return count;
}

int addTask2(CompoundJob job, JobController jobController, JobConfController jobConfController, JspWriter out, String dataName) throws Exception {
	int index = 0;
	int count = 0;
	for (JobDefine jd: job.getSubJobs()) {
		if (jd.isSkip()) continue;
		
		Job subJob = jobController.getJob(jd.getIdentifier());
		JobConf subConf = jobConfController.getJobConf(subJob.getJobConfIdentifier());
		if (CompoundJobConf.JOB_TYPE.equals(subJob.getType())) {
			count+=addTask2((CompoundJob)subJob, jobController, jobConfController, out, dataName);
		} else {
			out.println(dataName + ".push({ identifier:'" + subJob.getIdentifier().getStringIdentifier() + "', name:'" + subConf.getName() + "', resource:'" + subJob.getResource() + "', time:" + (subJob.getFinishTime() - subJob.getLaunchTime()) + " });");
			count++;
		}
		
		index++;
	}
	return count;
}
%>
<html>
	<head>
<jsp:include page="fragment/job-result-header.jsp"/>
<c:if test="${job.succeed}">
		<link rel="stylesheet" type="text/css" href="static/dhtmlx/dhtmlxgantt.css"/>
		<script type="text/javascript" language="javascript" src="static/dhtmlx/dhtmlxgantt.js"></script>
</c:if>
		<script type="text/javascript">
<c:if test="${job.succeed}">
			function createChartControl(htmlDiv1){
				var project1 = new GanttProjectInfo('${job.identifier.stringIdentifier}', "${conf.name}", new Date(${job.launchTime}));
<%addTask((CompoundJob)request.getAttribute("job"), (JobConf)request.getAttribute("conf"), (JobController)request.getAttribute("jobController"), (JobConfController)request.getAttribute("jobConfController"), out, null, 0);%>

				// Create Gantt control
				var dayInPixels = Math.ceil(${24 * 3600 * 1000 * 700 / (job.finishTime-job.launchTime)});
				var ganttChartControl = new GanttChart(dayInPixels, new Date(${job.launchTime - (job.finishTime-job.launchTime) / 20}));

				// Setup paths and behavior
				ganttChartControl.setImagePath("static/dhtmlx/imgs/");
				ganttChartControl.setStylePath("static/dhtmlx/dhtmlxgantt.css")
				ganttChartControl.setEditable(false);
				ganttChartControl.showTreePanel(true);
				ganttChartControl.showContextMenu(false);
				ganttChartControl.showDescTask(true,'d');
				ganttChartControl.showDescProject(true,'d');

				// Load data structure        
				ganttChartControl.addProject(project1);

				// Build control on the page
				ganttChartControl.create(htmlDiv1);
				
				$("#print").click(function(){
					ganttChartControl.printToWindow();
				});
			}
			
			function createChart(htmlDiv1) {
				var data = [];
<%addTask2((CompoundJob)request.getAttribute("job"), (JobController)request.getAttribute("jobController"), (JobConfController)request.getAttribute("jobConfController"), out, "data");%>

				var barChart = new dhtmlXChart({
					view: "pie",
					container: htmlDiv1,
					value: "#time#",
					sort:{
						by:"#time#",
						as:"int",
						dir:"desc"
					},
					pieInnerText: function(obj){
						var sum = barChart.sum("#time#");
						var rate = Math.round(parseFloat(obj.time) / sum * 100);
						if (rate>=5) {
							return rate + '%';
						}
					},
					label: function(obj){
						var sum = barChart.sum("#time#");
						var rate = Math.round(parseFloat(obj.time) / sum * 100);
						if (rate>=5) {
							return obj.id;
						}
					},
					tooltip:{
						template: function(obj){
							var sum = barChart.sum("#time#");
							var d = new Date();
							return obj.id + " (" + Math.round(parseFloat(obj.time) / sum * 100) + "%) " + d.between(new Date(d.getTime() - obj.time)) + 's';
						}
					},
					legend:{
						width: 300,
						align: "right",
						valign: "middle",
						template: function(obj){
							var sum = barChart.sum("#time#");
							return obj.id + " " + Math.round(parseFloat(obj.time) / sum * 100) + "%";
						},
						marker:{
							type: "round",
							width: 15
						}
					},
					gradient: true
				});
				barChart.parse(data, "json");
				$("input[name=groupBy]:radio").change(function(){
					barChart.group({
						by: $(this).val(),
						map:{
							time: ["#time#", "sum"]
						}
					});
				});
				$('input[name=groupBy][value="#resource#"]:radio').prop("checked", "checked").change();
			}
			
</c:if>
			function createTabBar(htmlDiv1) {
				var tabbar = new dhtmlXTabBar(htmlDiv1, "top");
				tabbar.setSkin('dhx_skyblue');
				tabbar.setImagePath("static/dhtmlx/imgs/");
				tabbar.addTab("a1", "子Job", "100px");tabbar.setContent("a1", "subJobs");
				<c:if test="${job.succeed}">tabbar.addTab("a2", "甘特图", "100px");tabbar.setContent("a2", "gantt");</c:if>
				<c:if test="${job.succeed}">tabbar.addTab("a3", "资源占比", "100px");tabbar.setContent("a3", "chart");</c:if>
				tabbar.enableAutoSize(true, true);
				tabbar.setTabActive("a1");
			}
			
			$(function(){
				createTabBar('TabBarDiv');
<c:if test="${job.succeed}">
				createChartControl('GanttDiv');
				createChart('ChartDiv');
</c:if>
			});
		</script>
	</head>
	<body>
<jsp:include page="fragment/job-result-base.jsp"/>
		<hr>
		<div id="TabBarDiv" style="width:100%; height:90px;"></div>
<c:if test="${job.succeed}">
		<div id="gantt">
			<div style="width:980px; height:410px; position:relative" id="GanttDiv"></div>
			<input id="print" type="button" value="Print Gantt Chart">
		</div>
		<div id="chart">
			<div id="ChartDiv" style="width:900px;height:410px;border:1px solid #A4BED4;"></div>
			Group By:<input type="radio" name="groupBy" value="#resource#">Resource<input type="radio" name="groupBy" value="#name#">Job<input type="radio" name="groupBy" value="#resource#:#name#">JobResource
		</div>
</c:if>
		<div id="subJobs">
		<table>
			<tr>
				<th>No.</th>
				<th>Job Id</th>
				<th>Type</th>
				<th>Name</th>
				<th>Description</th>
				<th>Parameters</th>
				<c:if test="${showDependency}"><th>Dependencies</th></c:if>
				<c:if test="${showCondition}"><th>Conditions</th></c:if>
				<th>LaunchTime</th>
				<th>FinishTime</th>
				<th>RunTime</th>
				<th>Status</th>
				<th>Result</th>
			</tr>
<c:forEach var="dt" items="${subJobs}" varStatus="vs">
			<tr>
				<td>${vs.index+1}</td>
				<td><c:if test="${!dt.jjd.skip}">
					<a href="${ss:getServerPath(pageContext.request)}/job-result.action?identifier=${dt.job.identifier.stringIdentifier}">${dt.job.identifier.stringIdentifier}</a>
				</c:if></td>
				<td>${dt.conf.type}</td>
				<td><a href="${ss:getServerPath(pageContext.request)}/job-conf.action?action=view&identifier=${dt.conf.identifier.stringIdentifier}">${dt.conf.name}</a></td>
				<td>${dt.conf.description}</td>
				<td><c:forEach var="pd" items="${dt.conf.parameters}">
	<c:choose>
		<c:when test="${ss:getMapValue(dt.cjd.parameters, pd.name)==null}">
					<b>${pd.name}</b>=预设值：${ss:getParameterDefineTypeName(pd.type)}<c:if test="${pd.type!='none'}">，内容：${pd.value}</c:if><br>
		</c:when>
		<c:otherwise>
					<b>${pd.name}</b>=${ss:getMapValue(dt.jjd.parameters, pd.name)}<br>
		</c:otherwise>
	</c:choose>
				</c:forEach></td>
				<c:if test="${showDependency}"><td>${dt.jjd.dependencies}</td></c:if>
				<c:if test="${showCondition}"><td>${dt.jjd.condition}</td></c:if>
				<td>${ss:dateFormat(dt.job.launchTime)}</td>
				<td>${ss:dateFormat(dt.job.finishTime)}</td>
				<td>${ss:timeBetween(dt.job.finishTime, dt.job.launchTime)}</td>
				<td>${dt.jjd.skip?'skip':dt.job.status}</td>
				<td>
					<c:if test="${dt.jjd.skip || ss:isFinished(dt.job.status)}">
<c:choose>
	<c:when test="${param.mail==null}">
						<c:choose>
							<c:when test="${dt.jjd.skip}"><img alt="skip" src="images/icons/remove.jpg" title="skip"></c:when>
							<c:when test="${dt.job.succeed}"><img alt="success" src="images/icons/ok.jpg" title="success"></c:when>
							<c:otherwise><img alt="fail" src="images/icons/error.png" title="fail"></c:otherwise>
						</c:choose>
	</c:when>
	<c:otherwise>
						<c:choose>
							<c:when test="${dt.jjd.skip}"><img alt="skip" src="cid:img_skip" title="skip"></c:when>
							<c:when test="${dt.job.succeed}"><img alt="success" src="cid:img_ok" title="success"></c:when>
							<c:otherwise><img alt="fail" src="cid:img_error" title="fail"></c:otherwise>
						</c:choose>
	</c:otherwise>
</c:choose>
					</c:if>
					<c:if test='${param.mail==null && !dt.jjd.skip && ss:isFinished(dt.job.status) && !dt.job.succeed}'>
						<a href="run-job-conf.action?action=reExecute&jobIdentifier=${dt.job.identifier.stringIdentifier}"><img alt="重新执行" src="images/icons/reload.png" title="重新执行"></a>
						<c:if test='${dt.job.type=="compound"}'>
							<a href="run-job-conf.action?action=reExecute&jobIdentifier=${dt.job.identifier.stringIdentifier}&failedOnly=true"><img alt="仅重新执行错误的" src="images/icons/reload2.png" title="仅重新执行错误的"></a>
						</c:if>
					</c:if>
				</td>
			</tr>
</c:forEach>
		</table>
	<c:if test='${conf.type == "loop"}'>
		<b>循环参数:</b> 变量：${conf.loopVar}，类型：${conf.loopType}，从：${conf.loopFrom} 到：${conf.loopTo}，步长：${conf.loopStep}，${conf.loopDependency?"顺序执行":"并发执行"}<BR>
	</c:if>
<jsp:include page="fragment/job-result-parameter.jsp"/>
		</div>
<jsp:include page="fragment/job-result-footer.jsp"/>
	</body>
</html>
